package com.anquing.socket01;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author Administrator
 *URL类方法测试
 */
public class TestURL {


	public static void main(String[] args) throws MalformedURLException {
		//创建一个URL实例
		URL url = new URL("https://www.baidu.com");
		//通过url创建一下新的url
		URL url2 = new URL(url,"index.html?username=tom#test");
		//url的一些方法
		System.out.println("协议："+url2.getProtocol());
		System.out.println("主机："+url2.getHost());
		System.out.println("端口："+url2.getPort());
		System.out.println("默认端口："+url2.getDefaultPort());
		System.out.println("文件路径："+url2.getPath());
		System.out.println("文件名称："+url2.getFile());
		System.out.println("相对路径（锚点）："+url2.getRef());
		System.out.println("查询字符串："+url2.getQuery());
		//使用url读取网页内容
		try {
			//通过URL的openStream方法获取URL对象表示的资源的字节输入流
			InputStream is = url.openStream();
			//将字节输入流转化成字符输入流
			InputStreamReader isr = new InputStreamReader(is,"utf-8");
			//为字符输入流添加缓冲
			BufferedReader br = new BufferedReader(isr);
			String data = br.readLine();//读取数据
			while(data!=null){//循环读取数据
				System.out.println(data);//输出数据
				data = br.readLine();
			}
			br.close();
			isr.close();
			is.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
